import { Component, OnInit } from '@angular/core';
import { Cash, CashService } from 'src/app/service/cash.service';
import { TableStyle, TableStyleService } from 'src/app/service/table-style.service';
import { CashType, CashTypeService } from 'src/app/service/cash-type.service';
import { ContactCompany, ContactCompanyService } from 'src/app/service/contact-company.service';
import { MessageService } from 'primeng/api';
import { NzNotificationService } from 'ng-zorro-antd';
import { BreadFieldService } from 'src/app/service/bread-field.service';
import { JsonResult } from 'src/app/model/JsonResult';
import { UUID } from 'angular2-uuid';
import { forkJoin, Subject } from 'rxjs';
import { Cash01Service } from 'src/app/service/cash01.service';
import { debounce, debounceTime } from 'rxjs/operators';
import { ENUM_AMOUNT_TYPE } from 'src/app/global/enum';
import { VariableService } from 'src/app/service/variable.service';

@Component({
  selector: 'app-cash01',
  templateUrl: './cash01.component.html',
  styleUrls: ['./cash01.component.css']
})
export class Cash01Component implements OnInit {
  ngOnInit(): void {}

  vari:{// 变量集合 - 属性集合
    'mouseOver_rowIndex':number,// 鼠标悬停的行号
    'emptyRowCount':number, // 空白行数
    'statistics':{ [key:string]:{ label:string,value:number } }, // 有统计的字段的集合
    'reqTip':string
  } = { mouseOver_rowIndex:-1,'emptyRowCount':1,'statistics':{},'reqTip':'请求失败，请检查网络连接！'};

  cashType:CashType[] = [];
  cc:ContactCompany[] = [];

  // 表格编辑用缓存数据
  cache:{
    detail:{ [key:string]:{ edit:boolean,data:Cash } }
  } = {
    'detail':{}
  }

  mouseOverUUID:string= '';

  private amount$ = new Subject();// 现金
  private credit_amount$ = new Subject();// 记账

  constructor(
    private pMsgService:MessageService,
    private noti:NzNotificationService,
    private tableStyleService:TableStyleService,
    public detailService:Cash01Service,
    public breadField:BreadFieldService,
    private cashTypeService:CashTypeService,
    private ccService:ContactCompanyService,
    private varService:VariableService
  ) { 
    this.init();
  }

  //#region 初始化rx对象
  initRx(){
    this.amount$.pipe(debounceTime(300)).subscribe(
      ( res:Cash ) => {
        if( res.amount >0 )
          this.detailService.editCache[res.uuid].data.amount_type = this.varService.amount_type.现金;
      },error => this.msg('现金金额变动导致了异常！')
    )

    this.credit_amount$.pipe(debounceTime(300)).subscribe(
      ( res:Cash ) => {
        if( res.credit_amount >0 ){
          console.log('记账金额大于0');
          this.detailService.editCache[res.uuid].data.amount_type = this.varService.amount_type.记账;
        }else{
          console.log('记账金额小于等于0');
        }
          
      },error => this.msg('记账金额变动导致了异常！')
    )

  }
  //#endregion

  //#region 初始化表格数据、样式数据、表格编辑状态下的下拉数据
  init(){
    // 查询获取表格编辑状态下的下拉数据
    this.detailService.initOpts().subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg('初始化下拉数据时出现异常！');
          return
        }
        
      },error => this.msg('初始化下拉数据时出现异常！')
    )

    this.initRx();// 初始化RX对象
    this.refresh();// 查询获取表格数据、样式数据
  }
  //#endregion

  onChange_amount(e){
    this.amount$.next(e);
  }

  onChange_camount(e){
    this.credit_amount$.next(e);
  }

  refresh(){
    this.detailService.refresh().subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg(res.msg);
          return
        }

        this.msg('刷新完毕！');
      },error => this.msg('刷新数据时出现异常！')
    )
  }

  //#region 鼠标移动相关的事件
  mouseOver(uuid:string){
  }

  mouseLeave(rowIndex:number){
  }
  //#endregion

  //#region 新增一个空行
  addEmptyRow(){
    this.detailService.addEmptyRow();
  }
  //#endregion

  //#region 开启编辑状态
  startEdit(rowIndex:number,uuid:string,event){
    event.preventDefault();
    const res:string = this.detailService.startEdit(uuid);
    if( res.length>0 )
      this.msg(res);
  }
  //#endregion

  //#region 取消编辑
  cancelEdit(rowIndex:number,uuid:string){
    this.detailService.editCache[uuid].edit = false;
  }
  //#endregion


  deleteRow(rowIndex:number,uuid:string){
    this.detailService.deleteRow(rowIndex,uuid).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg('删除数据时出错！');
          return
        }

        this.msg('删除成功！');
      },error => this.msg('删除数据时出现异常！')
    )
  }

  cancelDeleteRow(){
    // console.log('取消了删除行');
  }



  // 编辑状态下，编辑文本变动则对应修改其相关公式关联的字段的值
  inputChange(dataRow:Cash,tsRow:TableStyle){
    // let arr:{ fieldName:string,value:number }[] = this.breadField.triggerFormula(dataRow,tsRow,this.vari.tableStyle);
    // if( arr === undefined || arr === null || arr.length<=0 ) return
    // arr.forEach(ele => {
    //   this.cache.detail[dataRow.uuid].data[ele.fieldName] = ele.value;
    // });
    
    if( tsRow.field_name === 'amount' ){
      this.amount$.next(dataRow);
    }

    if( tsRow.field_name === 'credit_amount' ){
      this.credit_amount$.next(dataRow);
    }

  }
  


  updateCashType(type:string){
    this.detailService.updateCashType(type).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg(res.msg);
          return
        }

        this.msg('已更新项目分类！');
      },error => this.msg('更新项目分类时出现异常！')
    )
  }

  updateContactCompany(type:string){
    console.log('updateContactCompany:type = ' + type);
    let ccType:string = '';
    if( type === '收款' )
      ccType = '客户'
    else
      ccType = '供应商'

    console.log('即将更新' + ccType + '的往来单位');
    this.detailService.updateCC(ccType).subscribe(
      ( jr:JsonResult ) =>{
        if( jr.code !==1 ){
          this.msg(jr.msg);
          return
        }

        this.msg('已更新对应往来单位！');
      },error => this.msg(this.vari.reqTip)
    )
  }


  onChange_category(e){
    this.updateCashType(e);
    console.log('控制器中onChange_category的项目分类已更新完毕，即将开始更新往来单位！');
    this.updateContactCompany(e);
  }

  onChange_enum(e:string,fieldName:string){
    if( fieldName ==='colpay' ){
      this.updateCashType(e);
      this.updateContactCompany(e);
    }
  }

  filter(opts:string[],fieldName:string){
    this.detailService.filter(opts,fieldName);
  }


  //#region 自定义彩色消息通知
  msg(content:string) {
    this.pMsgService.add({key: 'custom', severity:'info', summary: '通知', detail:content});
  }
  //#endregion

  saveEdit(rowIndex:number,uuid:string){
    this.detailService.saveEdit(rowIndex,uuid).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg('保存时出现异常！');
          return
        }

        this.msg('保存完毕！');
      },error => this.msg('保存时出现异常！')
    )
  }

  printTD(){
    console.log(this.detailService.filterOpts);
  }


  restoreDeleted(rowIndex:number,uuid:string){
    this.detailService.restoreDeleted(this.detailService.tableDataDisplay[rowIndex].iid,rowIndex).subscribe(
      ( res:JsonResult ) =>{
        if( res.code !==1 ){
          this.msg(res.msg);
          return
        }

        this.msg('恢复成功！');
      },error => this.msg('恢复被删除数据时出现异常！')
    )
  }

}
